package stream.parallel;

import org.testng.Assert;
import org.testng.annotations.Test;
import util.MathUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class ParallelBase {

    static int seed = 1986249356;
    static List<Integer> list = new ArrayList<>();

    static {
        for (int i = 0; i < 50; i++) {
            list.add(new Random().nextInt(seed));
        }
    }


    /**
     * 并行流和串行流分解质因数
     * 当要处理的数达到50时，差距就很明显
     */
    @Test
    public void t1() {
        System.out.println(list);
        var list2 = new ArrayList<>(list);

//        LocalDateTime now = LocalDateTime.now();
        long t1 = System.currentTimeMillis();
        list.stream().parallel().forEach(MathUtil::resolvePrime);
//        LocalDateTime after = LocalDateTime.now();
        long t2 = System.currentTimeMillis();

        long t3 = System.currentTimeMillis();
        list2.stream().forEach(MathUtil::resolvePrime);
        long t4 = System.currentTimeMillis();

        System.out.println("cost " + (t2 - t1) + "ms"); // 16122ms
        System.out.println("cost " + (t4 - t3) + "ms"); // 54319ms
//        System.out.println(MathUtil.resolvePrime(9846230676408L));


    }

    public static void main(String[] args) {
        System.out.println(list);
        var list2 = new ArrayList<>(list);

//        LocalDateTime now = LocalDateTime.now();
        long t1 = System.currentTimeMillis();
        list.stream().parallel().forEach(MathUtil::resolvePrime);
//        LocalDateTime after = LocalDateTime.now();
        long t2 = System.currentTimeMillis();

        long t3 = System.currentTimeMillis();
        list2.stream().forEach(MathUtil::resolvePrime);
        long t4 = System.currentTimeMillis();

        System.out.println("cost " + (t2 - t1) + "ms");
        System.out.println("cost " + (t4 - t3) + "ms");
    }



}
